<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
use common\models\TagsModel;
class TagForm extends \yii\base\Model
{
    public $id;
    public $tags;
    
    public function rules() {
        return [
            ['tags','required'],
            ['tags','each','rule'=>['string']],
        ];
    }
    
    //保存标签集合
    public function saveTags(){
        $ids=[];
//        var_dump($this);exit;
        if(!empty($this->tags)){
            if(is_array($this->tags)){
                foreach ($this->tags as $tags=>$value) {
                $ids[]= $this->_saveTags();
            }
            }else{
                $ids[]= $this->_saveTags();
            }
            }
           
        return $ids;
    }
    //保存标签
    private function _saveTags(){
        $model=new TagsModel();
        $res=$model->find()->where(['tag_name'=>$tags])->one();
        //新建标签
        if(!$res){
            $model->tag_name=$tags;
            $model->post_num=1;
            if(!$model->save()){
                throw new Exception('保存标签失败');
            }
            return $model->id;
        }else {
            $res->updateCounters(['post_num'=>1]);//表示post_num自动加一    
        }
        return $res->id;
    }
}
